#!/bin/bash

# ============================================
# 修复后端连接问题
# ============================================

NGINX_CONF="/etc/nginx/conf.d/frontend.conf"

echo "=== 修复 Nginx 代理配置 ==="

# 1. 修改 proxy_pass 为本地地址
echo "修改 proxy_pass 配置..."
sudo sed -i 's|proxy_pass http://10.170.129.4:8000/api/;|proxy_pass http://127.0.0.1:8000/api/;|' "$NGINX_CONF"

echo "✓ 配置已更新"
grep "proxy_pass" "$NGINX_CONF" | grep -v "#"

# 2. 验证配置
echo ""
echo "验证配置..."
if sudo nginx -t; then
    echo "✓ 配置测试通过"
else
    echo "✗ 配置测试失败"
    exit 1
fi

# 3. 重新加载
echo ""
echo "重新加载 Nginx..."
sudo systemctl reload nginx

# 4. 测试后端 API
echo ""
echo "=== 测试后端 API ==="
echo "测试后端直接访问..."
curl -s http://127.0.0.1:8000/api/login/ 2>&1 | head -5 || echo "后端 API 路径可能不是 /api/login/"

echo ""
echo "测试 Nginx 代理..."
curl -s http://127.0.0.1/api/login/ 2>&1 | head -5 || echo "Nginx 代理可能有问题"

echo ""
echo "=== 检查 Django URL 配置 ==="
echo "查看 Django 的 URL 配置..."
echo "请检查 Django 项目的 urls.py 中是否正确配置了 /api/ 路径"

echo ""
echo "=== 常见 API 端点测试 ==="
echo "尝试访问常见的端点："
for endpoint in "api/login/" "api/init/settings/" "api/captcha/"; do
    echo -n "测试 /$endpoint: "
    curl -s -o /dev/null -w "%{http_code}" http://127.0.0.1:8000/$endpoint 2>/dev/null
    echo ""
done

echo ""
echo "✓ 修复完成！"
echo ""
echo "如果 API 仍然有问题，请检查："
echo "1. Django 的 urls.py 中是否正确配置了 'api/' 路径"
echo "2. Django 的 settings.py 中 CORS 配置是否正确"
echo "3. 前端构建时的 VITE_API_URL 配置"

